package cn.mengfly.product.repository;

import cn.mengfly.product.api.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;

/**
 * @author Mengfly
 * @date 2021/3/22 19:28
 */
@Repository
public class UserRedisRepository {


    public static final String USER_KEY_PRE = "user:";

    @Autowired
    private RedisTemplate<String, UserDto> userRedisTemplate;

    private ValueOperations<String, UserDto> operations;

    /**
     * 构造完毕后获取RedisTemplate中对值处理的对象
     */
    @PostConstruct
    private void init() {
        this.operations = this.userRedisTemplate.opsForValue();
    }

    public void saveUser(UserDto userDto) {
        this.operations.set(this.buildKey(userDto.getId()), userDto);
    }

    public UserDto findOne(Long userId) {
        String key = this.buildKey(userId);
        if (!this.userRedisTemplate.hasKey(key)) {
            return null;
        } else {
            return this.operations.get(key);
        }
    }

    public void delete(Long userId) {
        this.userRedisTemplate.delete(this.buildKey(userId));
    }

    protected String buildKey(Long userId) {
        return USER_KEY_PRE + userId;
    }
}
